Passed
Push — master ( 30a479...9fd386 )
by Muhammad Dyas
01:44
created

ActionHandler.startPoll   B

Complexity

Conditions 8

Size

Total Lines 47
Code Lines 36

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 36
dl 0
loc 47
rs 7.1493
c 0
b 0
f 0
cc 8
1
import {chat_v1 as chatV1} from '@googleapis/chat';
2
import BaseHandler from './BaseHandler';
3
import NewPollFormCard from '../cards/NewPollFormCard';
4
import {addOptionToState, getConfigFromInput, getStateFromCard} from '../helpers/state';
5
import {callMessageApi} from '../helpers/api';
6
import {createDialogActionResponse, createStatusActionResponse} from '../helpers/response';
7
import PollCard from '../cards/PollCard';
8
import {ClosableType, MessageDialogConfig, PollFormInputs, PollState, Voter} from '../helpers/interfaces';
9
import AddOptionFormCard from '../cards/AddOptionFormCard';
10
import {saveVotes} from '../helpers/vote';
11
import {PROHIBITED_ICON_URL} from '../config/default';
12
import ClosePollFormCard from '../cards/ClosePollFormCard';
13
import MessageDialogCard from '../cards/MessageDialogCard';
14
import {createAutoCloseTask} from '../helpers/task';
15
import ScheduleClosePollFormCard from '../cards/ScheduleClosePollFormCard';
16
17
/*
18
This list methods are used in the poll chat message
19
 */
20
interface PollAction {
21
  saveOption(): Promise<chatV1.Schema$Message>;
22
23
  getEventPollState(): PollState;
24
}
25
26
export default class ActionHandler extends BaseHandler implements PollAction {
27
  async process(): Promise<chatV1.Schema$Message> {
28
    const action = this.event.common?.invokedFunction;
29
    switch (action) {
30
      case 'start_poll':
31
        return await this.startPoll();
32
      case 'vote':
33
        return this.recordVote();
34
      case 'add_option_form':
35
        return this.addOptionForm();
36
      case 'add_option':
37
        return await this.saveOption();
38
      case 'show_form':
39
        const pollForm = new NewPollFormCard({topic: '', choices: []}, this.getUserTimezone()).create();
40
        return createDialogActionResponse(pollForm);
41
      case 'new_poll_on_change':
42
        return this.newPollOnChange();
43
      case 'close_poll_form':
44
        return this.closePollForm();
45
      case 'close_poll':
46
        return await this.closePoll();
47
      case 'schedule_close_poll_form':
48
        return this.scheduleClosePollForm();
49
      case 'schedule_close_poll':
50
        return this.scheduleClosePoll();
51
      default:
52
        return createStatusActionResponse('Unknown action!', 'UNKNOWN');
53
    }
54
  }
55
56
  /**
57
   * Handle the custom start_poll action.
58
   *
59
   * @returns {object} Response to send back to Chat
60
   */
61
  async startPoll(): Promise<chatV1.Schema$Message> {
62
    // Get the form values
63
    const formValues: PollFormInputs = this.event.common!.formInputs! as PollFormInputs;
64
    const config = getConfigFromInput(formValues);
65
66
    if (!config.topic || config.choices.length === 0) {
67
      // Incomplete form submitted, rerender
68
      const dialog = new NewPollFormCard(config, this.getUserTimezone()).create();
69
      return createDialogActionResponse(dialog);
70
    }
71
72
    if (config.closedTime) {
73
      // because previously in the form, we marked up the time with user timezone offset
74
      const utcClosedTime = config.closedTime + this.getUserTimezone().offset;
75
      if (utcClosedTime < Date.now() - 360000) {
76
        const dialog = new NewPollFormCard(config, this.getUserTimezone()).create();
77
        return createDialogActionResponse(dialog);
78
      }
79
      config.closedTime = utcClosedTime;
80
    }
81
82
    const pollCardMessage = new PollCard({author: this.event.user, ...config},
83
      this.getUserTimezone()).createMessage();
84
    const request = {
85
      parent: this.event.space?.name,
86
      requestBody: pollCardMessage,
87
    };
88
89
    const apiResponse = await callMessageApi('create', request);
90
    if (apiResponse.status === 200 && apiResponse.data?.name) {
91
      await createAutoCloseTask(config, apiResponse.data.name);
92
      return createStatusActionResponse('Poll started.', 'OK');
93
    } else if (apiResponse.status === 444) {
94
      return {
95
        actionResponse: {
96
          type: 'NEW_MESSAGE',
97
        },
98
        ...pollCardMessage,
99
      };
100
    } else {
101
      return createStatusActionResponse('Failed to start poll.', 'UNKNOWN');
102
    }
103
  }
104
105
  /**
106
   * Handle the custom vote action. Updates the state to record
107
   * the user's vote then rerenders the card.
108
   *
109
   * @returns {object} Response to send back to Chat
110
   */
111
  recordVote() {
112
    const parameters = this.event.common?.parameters;
113
    if (!(parameters?.['index'])) {
114
      throw new Error('Index Out of Bounds');
115
    }
116
    const choice = parseInt(parameters['index']);
117
    const userId = this.event.user?.name ?? '';
118
    const userName = this.event.user?.displayName ?? '';
119
    const voter: Voter = {uid: userId, name: userName};
120
    const state = this.getEventPollState();
121
122
    // Add or update the user's selected option
123
    state.votes = saveVotes(choice, voter, state.votes!, state.anon);
124
    const card = new PollCard(state, this.getUserTimezone());
125
    return {
126
      thread: this.event.message?.thread,
127
      actionResponse: {
128
        type: 'UPDATE_MESSAGE',
129
      },
130
      cardsV2: [card.createCardWithId()],
131
    };
132
  }
133
134
  /**
135
   * Opens and starts a dialog that allows users to add details about a contact.
136
   *
137
   * @returns {object} open a dialog.
138
   */
139
  addOptionForm() {
140
    const state = this.getEventPollState();
141
    const dialog = new AddOptionFormCard(state).create();
142
    return createDialogActionResponse(dialog);
143
  };
144
145
  /**
146
   * Handle add new option input to the poll state
147
   * the user's vote then rerenders the card.
148
   *
149
   * @returns {object} Response to send back to Chat
150
   */
151
  async saveOption(): Promise<chatV1.Schema$Message> {
152
    const userName = this.event.user?.displayName ?? '';
153
    const state = this.getEventPollState();
154
    const formValues = this.event.common?.formInputs;
155
    const optionValue = formValues?.['value']?.stringInputs?.value?.[0]?.trim() ?? '';
156
    addOptionToState(optionValue, state, userName);
157
158
    const cardMessage = new PollCard(state, this.getUserTimezone()).createMessage();
159
160
    const request = {
161
      name: this.event.message!.name,
162
      requestBody: cardMessage,
163
      updateMask: 'cardsV2',
164
    };
165
    const apiResponse = await callMessageApi('update', request);
166
    if (apiResponse.status === 200) {
167
      return createStatusActionResponse('Option is added', 'OK');
168
    } else if (apiResponse.status === 444) {
169
      return {
170
        thread: this.event.message?.thread,
171
        actionResponse: {
172
          type: 'UPDATE_MESSAGE',
173
        },
174
        ...cardMessage,
175
      };
176
    } else {
177
      return createStatusActionResponse('Failed to add option.', 'UNKNOWN');
178
    }
179
  }
180
181
  getEventPollState(): PollState {
182
    const stateJson = getStateFromCard(this.event);
183
    if (!stateJson) {
184
      throw new ReferenceError('no valid state in the event');
185
    }
186
    return JSON.parse(stateJson);
187
  }
188
189
  async closePoll(): Promise<chatV1.Schema$Message> {
190
    const state = this.getEventPollState();
191
    state.closedTime = Date.now();
192
    state.closedBy = this.event.user?.displayName ?? '';
193
    const cardMessage = new PollCard(state, this.getUserTimezone()).createMessage();
194
    const request = {
195
      name: this.event.message!.name,
196
      requestBody: cardMessage,
197
      updateMask: 'cardsV2',
198
    };
199
    const apiResponse = await callMessageApi('update', request);
200
    if (apiResponse.status === 200) {
201
      return createStatusActionResponse('Poll is closed', 'OK');
202
    } else if (apiResponse.status === 444) {
203
      return {
204
        thread: this.event.message?.thread,
205
        actionResponse: {
206
          type: 'UPDATE_MESSAGE',
207
        },
208
        ...cardMessage,
209
      };
210
    } else {
211
      return createStatusActionResponse('Failed to close poll.', 'UNKNOWN');
212
    }
213
  }
214
215
  closePollForm() {
216
    const state = this.getEventPollState();
217
    if (state.type === ClosableType.CLOSEABLE_BY_ANYONE || state.author!.name === this.event.user?.name) {
218
      return createDialogActionResponse(new ClosePollFormCard(state, this.getUserTimezone()).create());
219
    }
220
221
    const dialogConfig: MessageDialogConfig = {
222
      title: 'Sorry, you can not close this poll',
223
      message: `The poll setting restricts the ability to close the poll to only the creator(${state.author!.displayName}).`,
224
      imageUrl: PROHIBITED_ICON_URL,
225
    };
226
    return createDialogActionResponse(new MessageDialogCard(dialogConfig).create());
227
  }
228
229
  async scheduleClosePoll(): Promise<chatV1.Schema$Message> {
230
    const formValues: PollFormInputs = this.event.common!.formInputs! as PollFormInputs;
231
    const config = getConfigFromInput(formValues);
232
233
    // because previously in the form, we marked up the time with user timezone offset
234
    const utcClosedTime = config.closedTime! + this.getUserTimezone()?.offset;
235
    if (utcClosedTime < Date.now() - 360000) {
236
      const dialog = new ScheduleClosePollFormCard(config, this.getUserTimezone()).create();
237
      return createDialogActionResponse(dialog);
238
    }
239
    config.closedTime = utcClosedTime;
240
    const messageId = this.event.message!.name!;
241
    config.autoClose = true;
242
    await createAutoCloseTask(config, messageId);
243
244
    const state = this.getEventPollState();
245
    state.closedTime = utcClosedTime;
246
    const cardMessage = new PollCard(state, this.getUserTimezone()).createMessage();
247
248
    const request = {
249
      name: this.event.message!.name,
250
      requestBody: cardMessage,
251
      updateMask: 'cardsV2',
252
    };
253
    const apiResponse = await callMessageApi('update', request);
254
    if (apiResponse.status === 200) {
255
      return createStatusActionResponse('Poll is scheduled to close', 'OK');
256
    } else if (apiResponse.status === 444) {
257
      return createStatusActionResponse('Your admin need allow you using 3rd party application', 'UNKNOWN');
258
    } else {
259
      return createStatusActionResponse('Failed to schedule close poll. Unknown reason', 'UNKNOWN');
260
    }
261
  }
262
263
  scheduleClosePollForm() {
264
    const state = this.getEventPollState();
265
    return createDialogActionResponse(new ScheduleClosePollFormCard(state, this.getUserTimezone()).create());
266
  }
267
268
  newPollOnChange() {
269
    const formValues: PollFormInputs = this.event.common!.formInputs! as PollFormInputs;
270
    const config = getConfigFromInput(formValues);
271
    return createDialogActionResponse(new NewPollFormCard(config, this.getUserTimezone()).create());
272
  }
273
}
274